package com.qianyu.project.web.controller.base;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author gs
 * @date create in 2021/1/24 8:54
 */
@RestController
public class DownloadController {

    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    private static final String accessKeyId = "LTAI4GCXS6Qi9BqpB7S55n3u";

    private static final String accessKeySecret = "PfFpcEmXMvzUUChJAViMo9DcNcQkag";

    private static final String bucketName = "qy-file-bucket";

    @GetMapping("/download")
    public void download(String url, String name ,HttpServletResponse response) {
        try{
            String objectName = url.replace("https://qy-file-bucket.oss-cn-beijing.aliyuncs.com/", "").split("\\?")[0];
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            OSSObject ossObject = ossClient.getObject(bucketName, objectName);

            BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(name,"utf-8")+"."+StringUtils.getFilenameExtension(objectName));
            OutputStream outputStream = response.getOutputStream();
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[1024];
            int lenght = 0;

            while ((lenght = in.read(buffer)) != -1) {
                out.write(buffer, 0, lenght);
            }

            if (out != null) {
                out.flush();
                out.close();
            }

            if (in != null) {
                in.close();
            }

            ossClient.shutdown();
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
